package com.fy.fyspace.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fy.fyspace.common.config.AliYunAiApi;
import com.fy.fyspace.common.manager.AiTaskQueueManager;
import com.fy.fyspace.common.result.Result;
import com.fy.fyspace.constant.SysConstant;
import com.fy.fyspace.ex.ConditionException;
import com.fy.fyspace.mapper.AipictureMapper;
import com.fy.fyspace.mapper.PictureMapper;
import com.fy.fyspace.mapper.SpaceMapper;
import com.fy.fyspace.model.dto.outpainting.CreateOutPaintingTaskDTO;
import com.fy.fyspace.model.dto.outpainting.CreatePictureOutPaintingTaskDTO;
import com.fy.fyspace.model.entity.Aipicture;
import com.fy.fyspace.model.entity.Picture;
import com.fy.fyspace.model.entity.Space;
import com.fy.fyspace.model.enums.aipicture.AiPictureTaskStatusEnum;
import com.fy.fyspace.model.enums.picture.PictureDeleteStatusEnum;
import com.fy.fyspace.model.enums.space.SpaceTypeEnum;
import com.fy.fyspace.model.vo.outpainting.CreateOutPaintingTaskVO;
import com.fy.fyspace.model.vo.outpainting.GetOutPaintingTaskVO;
import com.fy.fyspace.model.vo.picture.AiPictureVO;
import com.fy.fyspace.model.vo.picture.AiTaskVO;
import com.fy.fyspace.model.vo.user.UserSessionVO;
import com.fy.fyspace.service.AIService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AIServiceImpl extends ServiceImpl<AipictureMapper, Aipicture> implements AIService {

  @Resource
  private AliYunAiApi aliYunAiApi;

  @Autowired
  private AiTaskQueueManager aiTaskQueueManager;

  @Value("${zhipu.ai.api-key:}")
  private String zhipuApiKey;

  @Resource
  private PictureMapper pictureMapper;

  @Resource
  private SpaceMapper spaceMapper;

  @Autowired
  private AipictureMapper aipictureMapper;


  /**
   * 创建 AI 扩图任务
   */
  @Override
  public CreateOutPaintingTaskVO createPictureOutPaintingTask(CreatePictureOutPaintingTaskDTO request,
                                                              UserSessionVO loginUser) {
    log.info("开始创建AI扩图任务: userId={}, pictureId={}", loginUser.getId(), request.getPictureId());

    // 获取图片信息
    Long pictureId = request.getPictureId();
    Picture picture = Optional.ofNullable(pictureMapper.selectById(pictureId))
            .orElseThrow(() -> new ConditionException("图片不存在"));
    log.info("获取到原始图片信息: pictureId={}, url={}", pictureId, picture.getUrl());

    // 创建扩图任务
    CreateOutPaintingTaskDTO createOutPaintingTaskRequest = new CreateOutPaintingTaskDTO();
    CreateOutPaintingTaskDTO.Input input = new CreateOutPaintingTaskDTO.Input();
    String imageUrl = SysConstant.DEFAULT_COS_PART_PATH + picture.getUrl();
    if (imageUrl.contains("?")) {
      imageUrl = imageUrl.substring(0, imageUrl.indexOf("?"));
      log.info("处理后的图片URL: {}", imageUrl);
    }
    input.setImageUrl(imageUrl);
    createOutPaintingTaskRequest.setInput(input);

    // 设置参数
    CreateOutPaintingTaskDTO.Parameters parameters = request.getParameters();
    if (parameters == null) {
      parameters = new CreateOutPaintingTaskDTO.Parameters();
      parameters.setTopOffset(100);
      parameters.setBottomOffset(100);
      parameters.setLeftOffset(100);
      parameters.setRightOffset(100);
      parameters.setBestQuality(true);
      parameters.setLimitImageSize(true);
      parameters.setAddWatermark(false);
      log.info("使用默认扩图参数: top={}, bottom={}, left={}, right={}",
              parameters.getTopOffset(), parameters.getBottomOffset(),
              parameters.getLeftOffset(), parameters.getRightOffset());
    } else {
      log.info("使用自定义扩图参数: top={}, bottom={}, left={}, right={}",
              parameters.getTopOffset(), parameters.getBottomOffset(),
              parameters.getLeftOffset(), parameters.getRightOffset());
    }
    createOutPaintingTaskRequest.setParameters(parameters);

    // 获取用户空间信息
    LambdaQueryWrapper<Space> w = new LambdaQueryWrapper<>();
    w.eq(Space::getUserId, loginUser.getId())
            .eq(Space::getSpaceType, SpaceTypeEnum.PERSONAL.getSpaceType());
    Space space = spaceMapper.selectOne(w);

    // 创建任务
    CreateOutPaintingTaskVO task = aliYunAiApi.createOutPaintingTask(createOutPaintingTaskRequest);
    String taskId = task.getOutput().getTaskId();
    log.info("AI扩图任务创建成功: taskId={}, status={}", taskId, task.getOutput().getTaskStatus());

    // 保存任务信息到数据库
    Aipicture aipicture = new Aipicture();
    aipicture.setTaskId(taskId);
    aipicture.setTaskStatus(task.getOutput().getTaskStatus());
    aipicture.setPicName(picture.getName());
    aipicture.setSpaceId(space.getId());
    aipicture.setUserId(loginUser.getId());
    aipicture.setPicId(pictureId);
    aipicture.setUrl(picture.getUrl());
    aipicture.setThumbnailUrl(picture.getThumbnailUrl());
    aipicture.setIsDelete(PictureDeleteStatusEnum.NOT_DELETE.getValue());
    aipicture.setCreateTime(new Date());
    this.save(aipicture);

    aiTaskQueueManager.addTask(taskId);

    if (StrUtil.isNotBlank(task.getCode())) {
      log.error("AI扩图任务创建异常: taskId={}, code={}, message={}",
              taskId, task.getCode(), task.getMessage());
    }

    return task;
  }

  /**
   * 获取 AI 扩图任务进度
   */
  @Override
  public GetOutPaintingTaskVO getOutpaintingTaskStatus(String taskId) {
    log.info("开始查询AI扩图任务状态: taskId={}", taskId);

    // 查询任务状态
    GetOutPaintingTaskVO taskStatus = aliYunAiApi.getOutPaintingTask(taskId);

    // 记录任务状态
    log.info("AI扩图任务状态: taskId={}, status={}", taskId, taskStatus.getOutput().getTaskStatus());

    // 如果任务成功且有输出URL，记录URL信息
    if ("SUCCEEDED".equals(taskStatus.getOutput().getTaskStatus())
            && StrUtil.isNotBlank(taskStatus.getOutput().getOutputImageUrl())) {
      log.info("AI扩图任务成功，输出URL: {}, 有效期约为30分钟", taskStatus.getOutput().getOutputImageUrl());
    }

    // 更新数据库中的任务状态
    LambdaQueryWrapper<Aipicture> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Aipicture::getTaskId, taskId);
    Aipicture aipicture = getOne(wrapper);
    if (aipicture != null) {
      aipicture.setTaskStatus(taskStatus.getOutput().getTaskStatus());
      if ("SUCCEEDED".equals(taskStatus.getOutput().getTaskStatus())) {
        aipicture.setUrl(taskStatus.getOutput().getOutputImageUrl());
      }
      updateById(aipicture);
    }

    return taskStatus;
  }

  /**
   * 获取 AI 扩图图片
   *
   * @param page
   * @param pageSize
   * @param prompt
   * @return
   */
  @Override
  public Result getAIPictures(Integer page, Integer pageSize, String prompt) {
    page = page == null ? 1 : page;
    pageSize = pageSize == null ? 10 : pageSize;

    LambdaQueryWrapper<Aipicture> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Aipicture::getTaskStatus, AiPictureTaskStatusEnum.SUCCESS.getCode())
            .like(StrUtil.isNotBlank(prompt), Aipicture::getPicName, prompt)
            .orderByDesc(Aipicture::getCreateTime);

    Page<Aipicture> aiPicturePage = new Page<>(page, pageSize);
    Page<Aipicture> resultPage = baseMapper.selectPage(aiPicturePage, wrapper);

    // 构建返回结果
    Map<String, Object> result = new HashMap<>();
    result.put("total", resultPage.getTotal());
    result.put("list", resultPage.getRecords().stream()
            .map(this::convertToAiPictureVO)
            .collect(Collectors.toList()));

    return Result.success(result);
  }

  /**
   * 获取 AI 任务列表
   *
   * @param page
   * @param pageSize
   * @param prompt
   * @param taskStatus
   * @return
   */
  @Override
  public Result getAITasks(Integer page, Integer pageSize, String prompt, String taskStatus) {
    // 设置默认值
    page = page == null ? 1 : page;
    pageSize = pageSize == null ? 10 : pageSize;

    // 构建查询条件
    LambdaQueryWrapper<Aipicture> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Aipicture::getIsDelete, PictureDeleteStatusEnum.NOT_DELETE.getValue());
    
    // 如果有任务状态筛选
    if (StrUtil.isNotBlank(taskStatus)) {
        queryWrapper.eq(Aipicture::getTaskStatus, taskStatus);
    }
    
    // 如果有搜索关键词
    if (StrUtil.isNotBlank(prompt)) {
        queryWrapper.like(Aipicture::getPicName, prompt);
    }
    
    // 按创建时间倒序排序
    queryWrapper.orderByDesc(Aipicture::getCreateTime);

    // 执行分页查询
    Page<Aipicture> pageResult = page(new Page<>(page, pageSize), queryWrapper);
    
    // 转换为VO对象
    List<AiTaskVO> taskVOList = pageResult.getRecords().stream()
            .map(task -> {
                AiTaskVO vo = new AiTaskVO();
                BeanUtils.copyProperties(task, vo);
                return vo;
            })
            .collect(Collectors.toList());

    // 构建返回结果
    Map<String, Object> result = new HashMap<>();
    result.put("records", taskVOList);
    result.put("total", pageResult.getTotal());
    result.put("size", pageResult.getSize());
    result.put("current", pageResult.getCurrent());
    result.put("pages", pageResult.getPages());

    return Result.success(result);
  }

  /**
   * 转换为AI图片VO对象
   */
  private AiPictureVO convertToAiPictureVO(Aipicture aiPicture) {
    AiPictureVO vo = new AiPictureVO();
    BeanUtils.copyProperties(aiPicture, vo);
    AiPictureTaskStatusEnum statusEnum = AiPictureTaskStatusEnum.getByCode(aiPicture.getTaskStatus());
    vo.setTaskStatusDesc(statusEnum.getDesc());
    vo.setCreateTime(aiPicture.getCreateTime());
    return vo;
  }

  /**
   * 转换为AI任务VO对象
   */
  private AiTaskVO convertToAiTaskVO(Aipicture aiPicture) {
    AiTaskVO vo = new AiTaskVO();
    BeanUtils.copyProperties(aiPicture, vo);
    return vo;
  }

  /**删除AI图片
   *
   * @param ids AI图片ID字符串，多个ID用逗号分隔
   * @return
   */

  @Override
  public Result deleteAIPictures(String ids) {
    try {
      log.info("开始删除AI图片: ids={}", ids);

      if (StrUtil.isBlank(ids)) {
        log.warn("删除失败：ID为空");
        return Result.error("请选择要删除的图片");
      }

      // 将ids字符串转换为List<Long>
      List<Long> idsList = new ArrayList<>();
      try {
        String[] idsArr = ids.split(",");
        for (String id : idsArr) {
          if (StrUtil.isNotBlank(id)) {
            try {
              idsList.add(Long.parseLong(id.trim()));
            } catch (NumberFormatException e) {
              log.error("ID格式错误: {}", id);
              return Result.error("ID格式错误: " + id);
            }
          }
        }
      } catch (Exception e) {
        log.error("解析ID列表失败", e);
        return Result.error("ID格式错误");
      }

      if (idsList.isEmpty()) {
        return Result.error("请选择要删除的图片");
      }

      // 更新删除状态
      int successCount = 0;
      for (Long id : idsList) {
        Aipicture aipicture = aipictureMapper.selectById(id);
        if (aipicture != null) {
          aipicture.setIsDelete(PictureDeleteStatusEnum.IS_DELETE.getValue());
          aipicture.setUpdateTime(new Date());
          int rows = aipictureMapper.updateById(aipicture);
          if (rows > 0) {
            successCount++;
            log.info("成功删除AI图片: id={}", id);
          }
        } else {
          log.warn("找不到对应的AI图片: id={}", id);
        }
      }

      log.info("批量删除AI图片完成: 总数={}, 成功数={}", idsList.size(), successCount);
      return Result.success("成功删除" + successCount + "张图片");
    } catch (Exception e) {
      log.error("删除AI图片失败", e);
      return Result.error("删除失败：" + e.getMessage());
    }
  }
}